package cn.cxyxj.study04.Authentication;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class LoginController {

    @Autowired
    private Producer producer;

    /**
     * 生成验证码
     */
    @GetMapping("/verify-code")
    public void getVerifyCode(HttpServletResponse resp, HttpSession session) throws IOException {
        resp.setContentType("image/jpeg");
        // 生成图形校验码内容
        String text = producer.createText();
        // 将验证码内容存入HttpSession
        session.setAttribute("verify_code", text);
        // 生成图形校验码图片
        BufferedImage image = producer.createImage(text);
        // 使用try-with-resources 方式，可以自动关闭流
        try(ServletOutputStream out = resp.getOutputStream()) {
            // 将校验码图片信息输出到浏览器
            ImageIO.write(image, "jpeg", out);
        }
    }
}
